package com.lam.common.pay.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.lam.common.utils.StringUtils;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;

@Configuration
@ConditionalOnClass({WxMaService.class, WxPayService.class})
@EnableConfigurationProperties(WxProperties.class)
public class WxConfig {
	
	@Autowired
    private WxProperties wxProperties;

    /**
     * 小程序配置
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public WxMaConfig wxMaConfig() {
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(this.wxProperties.getAppId());
        config.setSecret(this.wxProperties.getSecret());
        return config;
    }

    @Bean
    public WxMaService wxMaService(WxMaConfig maConfig) {
        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(maConfig);
        return service;
    }

    /**
     * 支付配置
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public WxPayService wxService() {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(StringUtils.trimToNull(this.wxProperties.getAppId()));
        payConfig.setMchId(StringUtils.trimToNull(this.wxProperties.getMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(this.wxProperties.getMchKey()));
        payConfig.setKeyPath(StringUtils.trimToNull(this.wxProperties.getKeyPath()));
        payConfig.setTradeType(StringUtils.trimToNull(this.wxProperties.getTradeType()));
        payConfig.setNotifyUrl(StringUtils.trimToNull(this.wxProperties.getNotifyUrl()));

        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(true);

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }
}

